/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.q1cc.cfs.jamp;


import net.q1cc.cfs.jamp.players.DefaultPlayerHandler;
import net.q1cc.cfs.jamp.players.PlayerHandler;
import net.q1cc.cfs.jamp.event.EventReporter;
import net.q1cc.cfs.jamp.players.MiniPlayerGui;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;


/**
 *
 * @author nixnick
 */
public class Main {
    PlayerHandler playerHandler;
    public MiniPlayerGui miniPlayerGui;
    BigGUI bigGUI;
    static Main main;
    Thread guiThread;
    Thread bigGuiThread;
    DBHandler dbHandler;
    Properties settings;
    EventReporter eventReporter;
    
    String databaseFolder;
    
    //TODO add logger
    
    boolean waitingForRestart=false;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main();


    }
    
    public Main()
    {
        init();
    }
    private void init()
    {
        try {
            main = this;
            eventReporter=new EventReporter();
            readDefaultConfig();
            settings = new Properties(settings);
            readSettings();
            addExitHook();
            
            dbHandler = new DBHandler(settings.getProperty("sql.host"), settings.getProperty("sql.user"), settings.getProperty("sql.passwd"), settings.getProperty("sql.database"), settings.getProperty("sql.table_prefix"));
            DBImporter importer = new DBImporter(dbHandler,null);
            importer.checkCreateTables();
            
            dbHandler.useQuery(null);
            
            miniPlayerGui = new MiniPlayerGui();
            guiThread = new Thread(miniPlayerGui);
            guiThread.setPriority(Math.round((Thread.MAX_PRIORITY + Thread.NORM_PRIORITY) / 2));
            guiThread.start();
            bigGUI = new BigGUI();
            bigGuiThread = new Thread(bigGUI);
            bigGuiThread.setPriority(Math.round((Thread.MAX_PRIORITY + Thread.NORM_PRIORITY) / 2));
            bigGuiThread.start();
            //System.getProperties().list(System.out);
        } catch (SQLException ex) {
            //Display error
            //JOptionPane.showMessageDialog(null, "Could not connect to MySQL Server, please give me one", "Error", JOptionPane.ERROR_MESSAGE);
            //ask for alt input
            //waitingForRestart=true;
            //new SettingsDialog(null,false).setVisible(true);
            ex.printStackTrace();
            System.exit(0);
        } catch (ClassNotFoundException ex) {
            System.out.println("Something is wrong with your classpath or the downloaded archive.");
        }
    }
    public void addExitHook()
    {
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run()
            {
                exit();
            }
        });
    }
    public static String[] files = {
                "/home/claus/Music/iTunes/iTunes Music/Music/Deadmau5/4x4=12/01 Some Chords.mp3",
                "resources/04 Furious Angels.mp3",
                ""
            };
    
    public void readDefaultConfig()
    {
        settings = new Properties();
        settings.setProperty("sql.host", "localhost");
        settings.setProperty("sql.user", "java");
        settings.setProperty("sql.passwd", "javaisttoll");
        settings.setProperty("sql.database", "java");
        settings.setProperty("sql.table_prefix", "tunes_");
        settings.setProperty("db.folder","");
    }
    public void readSettings()
    {
        try {
            File file = new File("settings.xml");
            if(file.canRead())
            {
                try{
                    settings.loadFromXML(new FileInputStream(file));
                } catch(java.util.InvalidPropertiesFormatException e)
                {
                    readDefaultConfig();
                    saveSettings();
                }
            } else {
                if(file.exists())
                {
                    System.out.println("ERROR: CANNOT READ CONFIG FILE");
                } else {
                    file.createNewFile();
                }
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
    public void saveSettings()
    {
        try {
            File file = new File("settings.xml");
            if(file.canRead())
            {
                file.delete();
                settings.storeToXML(new FileOutputStream(file), null);
            } else {
                System.out.println("ERROR: CANNOT READ CONFIG FILE");
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        if(waitingForRestart)
        {
            waitingForRestart=false;
            java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                init();
            }
        });
        }

    }
    public PlayerHandler getPlayer()
    {
        if(playerHandler!=null)
        {
            return playerHandler;
        } else {
            return playerHandler=new DefaultPlayerHandler();
        }
    }
    
    
    public static Main getInstance()
    {
        return main;
    }
    private boolean exiting=false;
    public void exit()
    {
        if(exiting)
            return;
        else
            exiting=true;
        if(playerHandler!=null)
        {
            playerHandler.destroy();
        }
        if (miniPlayerGui != null)
            miniPlayerGui.dispose();
        if (bigGUI!=null)
            bigGUI.dispose();
        
        System.exit(0);
    }
    

    public EventReporter getEventReporter() {
        return eventReporter;
    }
}
